package helloworld.security;

import helloworld.entity.administrate.Authority;
import helloworld.entity.administrate.Role;
import helloworld.entity.administrate.User;
import helloworld.service.administrate.IUserService;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.google.common.collect.Sets;

@Service
public class UserDetailService implements UserDetailsService {

	private IUserService userService;
	
	
	@Autowired
	public void setUserService(@Qualifier("userServiceClient")IUserService userService) {
		this.userService = userService;
	}

	public UserDetails loadUserByUsername(String userName)
			throws UsernameNotFoundException, DataAccessException {
		
		
		
		User user = userService.getUserByUsername(userName);
		
		if (user == null) {
			throw new UsernameNotFoundException("用户" + userName + " 不存在");
		}
		Set<GrantedAuthority> authSet = Sets.newHashSet();
		for (Role role : user.getRoleList()) {
			for (Authority authority : role.getAuthorityList()) {
				authSet.add(new GrantedAuthorityImpl(authority.getName()));
			}
		}
		UserDetails userdetails = new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), true, true, true, true, authSet);
		return userdetails;
	}

}
